<?php
/**
 * Created by PhpStorm.
 * User: yandian
 * Date: 16/8/6
 * Time: 15:40
 */

namespace app\weixin\services;

use app\common\model\Coral;
use app\common\model\Donation;
use app\common\model\MemberCoupon;
use app\common\model\MemberLuck;
use app\common\model\Prize;
use app\common\util\DateTimeUtil;
use app\common\util\LogUtil;

require_once APP_PATH . '../lib/wxpayapi/lib/WxPay.Notify.php';

class WxpayNotifyService extends \WxPayNotify
{

    private function isOrderExists($transaction_id)
    {
        $input = new \WxPayOrderQuery();
        $input->SetTransaction_id($transaction_id);
        $result = \WxPayApi::orderQuery($input);
        if (isset($result['return_code']) && isset($result['result_code'])
            && $result['result_code'] == 'SUCCESS' && $result['return_code'] == 'SUCCESS'
        ) {
            return true;
        }
        return false;
    }

    public function NotifyProcess($data, &$msg)
    {
        if (!isset($data['transaction_id'])) {
            $msg = '参数错误';
            return false;
        }

        if (!$this->isOrderExists($data['transaction_id'])) {
            $msg = '订单不存在';
            ccnn_syslog($msg);
            return false;
        }
        try {
            $attachment = json_decode($data['attach'], true);
            $billId = intval($attachment['billId']);
            $cash_fee = intval($data['cash_fee']);
            $billRow = Donation::instance()->where(['id' => $billId, 'status' => 0])->find();
            if (empty($billRow)) {
                $msg = '订单不存在或该订单已支付';
                ccnn_syslog($msg);
                return false;
            }
            $this->doTask($billRow);
        } catch (\Exception $ex) {
            ccnn_syslog($ex->getMessage());
            LogUtil::error($ex->getMessage());
        }
        return parent::NotifyProcess($data, $msg);
    }


    private function doTask($billRow)
    {
        $mid = $billRow['member_id'];
        $billId = $billRow['id'];
        $m = intval($billRow['money'] / 100);
        $now = DateTimeUtil::now();
        $coral = Coral::instance();
        $coral->startTrans();
        Donation::instance()->where(['id' => $billId])->save([
            'status' => 1,
            'pay_time' => $now
        ]);
        if ($m < 500) { // 中奖概率 珊瑚命名权
            //捐赠金额和中奖概率，【爱心小礼物，珊瑚命名权]
            $rates = [5 => [0.1, 0.01], 10 => [0.2, 0.02], 50 => [0, 0.1], 100 => [0, 0.2]];
            if (!empty($rates[$m])) {
                $rate = $rates[$m];
                //抽奖概率
                MemberLuck::instance()->add([
                    'member_id' => $mid,
                    'gift_rate' => $rate[0]*100,
                    'coral_rate' => $rate[1]*100,
                    'create_time' => DateTimeUtil::now(),
                    'status' => 0,
                    'donation_id' => $billId
                ]);
                if ($m >= 50) { // 爱心小礼物
                    Prize::instance()->add([
                        'member_id' => $mid,
                        'num' => 1,
                        'status' => 0,
                        'luck_id' => 0,
                        'luck_time' => DateTimeUtil::now()
                    ]);
                }
            }

        } else {
            // 500：  可获得爱心捐赠证书，1株珊瑚的命名权。
            // 5000元——可获得爱心捐赠证书，5株珊瑚的命名权，1人两次参与珊瑚种植保育潜水活动。
            //10000元——可获得爱心捐赠证书，10株珊瑚的命名权，2人两次参与珊瑚种植保育潜水活动。
            //50000元——可获得爱心捐赠奖牌，珊瑚公益基金荣誉个人（单位），一座珊瑚礁的命名权，4人两次参与珊瑚种植保育潜水活动，相关保育信息。
            \app\common\model\LoveCertificate::instance()->add([
                'member_id' => $mid,
                'donation_id' => $billId,
                'create_time' => $now
            ]);
            if ($m == 500) {
                $coral->add([
                    'member_id' => $mid,
                    'title' => '',
                    'donation_id' => $billId,
                    'create_time' => $now,
                    'coral_no' => ($coral->where(['member_id' => $mid])->max('coral_no') ?: 0) + 1
                ]);
            } elseif ($m == 5000) {
                $no = ($coral->where(['member_id' => $mid])->max('coral_no') ?: 0) + 1;
                for ($i = 0; $i < 5; $i++) {
                    $coral->add([
                        'member_id' => $mid,
                        'title' => '',
                        'donation_id' => $billId,
                        'create_time' => $now,
                        'coral_no' => $no++
                    ]);
                }
                //1人两次参与珊瑚种植保育潜水活动。
                for ($i = 0; $i < 2; $i++) {
                    MemberCoupon::instance()->add([
                        'coupon_id' => 0,
                        'member_id' => $mid,
                        'man_num' => 1,
                        'status' => 0,
                        'create_time' => $now,
                    ]);
                }
            } elseif ($m == 10000) {
                //10000元——可获得爱心捐赠证书，10株珊瑚的命名权，2人两次参与珊瑚种植保育潜水活动。
                $no = ($coral->where(['member_id' => $mid])->max('coral_no') ?: 0) + 1;
                for ($i = 0; $i < 10; $i++) {
                    $coral->add([
                        'member_id' => $mid,
                        'title' => '',
                        'donation_id' => $billId,
                        'create_time' => $now,
                        'coral_no' => $no++
                    ]);
                }
                //2人两次参与珊瑚种植保育潜水活动。
                for ($i = 0; $i < 2; $i++) {
                    MemberCoupon::instance()->add([
                        'coupon_id' => 0,
                        'member_id' => $mid,
                        'man_num' => 2,
                        'status' => 0,
                        'create_time' => $now,
                    ]);
                }
            } elseif ($m == 50000) {
                $coralReel = \app\common\model\CoralReef::instance();
                //一座珊瑚礁的命名权
                $no = ($coralReel->where(['member_id' => $mid])->max('coral_no') ?: 0) + 1;
                $coralReel->add([
                    'member_id' => $mid,
                    'title' => '',
                    'donation_id' => $billId,
                    'create_time' => $now,
                    'coral_no' => $no
                ]);
                //4人两次参与珊瑚种植保育潜水活动
                for ($i = 0; $i < 2; $i++) {
                    MemberCoupon::instance()->add([
                        'coupon_id' => 0,
                        'member_id' => $mid,
                        'man_num' => 4,
                        'status' => 0,
                        'create_time' => $now,
                    ]);
                }
            }
        }
        $coral->commit();
    }


    private function refund($data)
    {
        $input = new \WxPayRefund();
        $input->SetTransaction_id($data['transaction_id']);
        $input->SetRefund_fee($data['total_fee']);
        $input->SetTotal_fee($data['total_fee']);
        $input->SetOp_user_id($data['mch_id']);
        $input->SetOut_refund_no($data['out_trade_no']);
        \WxPayApi::refund($input);
    }

}